/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { connect, useDispatch, useSelector } from "dva";
import { Form, Table, Input, Button, Icon, Row, Col } from "antd";
import { useFormTable } from "@umijs/hooks";
import AsyncDownLoad from "@/components/DownloadBar/AsyncDownLoad";
import { dataCenterExport } from "@/services/platform";
import BindPost from "../components/BindPost";
import UnbindButton from "../components/UnbindButton";

const FormItem = Form.Item;

const DataTable = props => {
  const dispatch = useDispatch();
  const { bindYz, isCityLeague } = useSelector(({ platform }) => platform);
  const { form, activeKey } = props;
  const { getFieldDecorator } = form;
  const [type, setType] = useState("courier");
  const [showBind, setShowBind] = useState(true);
  const tableCount = useRef(null);
  const params = useRef({ type: "courier" });

  useEffect(
    () => {
      if (activeKey == "operator") {
        setType("courier");
        params.current = { type: "courier" };
      } else {
        params.current = { type: "dak" };
        setType("dak");
      }
    },
    [activeKey]
  );

  const getTableData = useCallback(
    ({ current, pageSize }, formData) => {
      return dispatch({
        type: "dataCenter/wxGetDataCenterList",
        payload: {
          page: current,
          size: pageSize,
          type,
          ...formData,
        },
      })
        .then(res => {
          const { data = {} } = res;
          const { total, list } = data;
          bindYz && setShowBind(false);
          if (current == 1) {
            // 缓存总数
            tableCount.current = total;
          }
          return {
            total: tableCount.current,
            list,
          };
        })
        .catch(code => {
          if (code == 9999) {
            setShowBind(true);
          }
        });
    },
    [type, dispatch, bindYz]
  );

  const { tableProps, search, loading } = useFormTable(getTableData, {
    defaultPageSize: 20,
    form,
  });

  const { pagination: tablePagination, onChange } = tableProps;

  const { submit } = search;

  const columns = useMemo(
    () => [
      {
        dataIndex: "num",
      },
      {
        title: type == "dak" ? "驿站" : "业务员",
        dataIndex: "name",
      },
      {
        title: type == "dak" ? "驿站账号" : "业务员账号",
        dataIndex: "account",
      },
      {
        title: type == "dak" ? "驿站地址" : "站点",
        dataIndex: "address",
      },
      {
        title: "公众号本月粉丝",
        dataIndex: "weixin.monthCount",
      },
      {
        title: "公众号累计粉丝",
        dataIndex: "weixin.allCount",
      },
      {
        title: "小程序本月粉丝",
        dataIndex: "weixin_mini.monthCount",
      },
      {
        title: "小程序累计粉丝",
        dataIndex: "weixin_mini.allCount",
      },
    ],
    [type]
  );

  const handleSearch = e => {
    e.preventDefault();
    submit();
  };

  if (type === "dak" && !isCityLeague && !bindYz && showBind) {
    return <BindPost pagination={tablePagination} refresh={onChange} />;
  }

  return (
    <>
      <Form layout="inline" onSubmit={handleSearch} style={{ marginBottom: 15 }}>
        <Row type="flex" justify="space-between">
          <Col>
            <FormItem>
              {getFieldDecorator("search")(
                <Input
                  prefix={<Icon type="search" />}
                  style={{ width: 300 }}
                  placeholder={
                    activeKey == "operator"
                      ? "请输入业务员姓名或账号搜索"
                      : "请输入快宝驿站名称或账号搜索"
                  }
                />
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit" loading={loading}>
                搜索
              </Button>
            </FormItem>
          </Col>
          <Col>
            {type === "dak" &&
              !isCityLeague && (
                <FormItem>
                  <UnbindButton onRefresh={submit} />
                </FormItem>
              )}
            <FormItem>
              <AsyncDownLoad requestFunc={() => dataCenterExport(params.current)}>
                <Button type="primary">导出</Button>
              </AsyncDownLoad>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Table
        rowKey="id"
        columns={columns}
        {...tableProps}
        pagination={{
          ...tablePagination,
          showTotal: all => `总数：${all}`,
        }}
      />
    </>
  );
};

export default connect()(Form.create()(DataTable));
